﻿{extend name="public:base" /}

{block name="css"}
<link rel="stylesheet" type="text/css" href="__STATIC__/layui-select/css/layui.css"/>
<link rel="stylesheet" type="text/css" href="__ADMIN__/css/style.css">

<style>
    .layui-form-select {
        position: relative;
        margin-bottom: 10px;
    }

    layui-progress-big, .layui-progress-big .layui-progress-bar {
        height: 30px;
        line-height: 30px
    }

    .layui-progress {
        position: relative;
        height: 30px;
        border-radius: 20px;
        background-color: #eee;
    }

    .layui-progress-text {
        position: relative;
        top: -20px;
        line-height: 30px;
        font-size: 12px;
        color: #666;
    }

    #ppt_show {
        width: 100%;
        height: 32px;
        line-height: 32px;
        text-align: center;
        font-size: 16px;
        border: 1px dotted #000;
    }

    .topic {
        border: 1px solid #cecdcd;
        margin: 10px 0;
    }

    .active {
        background: #fbcca5;
    }

    .topic .text {
        margin: 5px;
    }

    .topic img {
        width: calc((100% - 66px) / 5);
        height: 74px;
        object-fit: cover;
        margin: 5px;
        cursor: pointer;
    }
</style>{/block}

{block name="content"}

<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox ">
                <div class="ibox-content">
                    <form method="post" class="layui-form">
                        <div class="box-item">
                            <div class="box-item">
                                <div class="form-group row">
                                    <label class="col-sm-1 col-form-label">标题</label>
                                    <div class="col-sm-3">
                                        <input type="text" class="form-control" name="title" placeholder="请输入标题" value="{$info.title}">
                                    </div>
                                </div>
                                <div class="hr-line-dashed"></div>
                            </div>

                            <div class="form-group row"><label class="col-sm-1 col-form-label">封面图</label>
                                <div class="col-sm-6">
                                    <input type="file" id="img_file" accept="image/*" style="display: none">
                                    <input type="hidden" class="hidden_value" name="img" id="img" value="{$info['img']|default=''}"/>
                                    <div class="btn btn-w-m btn-primary" onclick="uploadImage('img_file', 'img', 'form-uploaded-box-single', false, 1)">原图上传</div>
                                    <div class="btn btn-w-m btn-primary" onclick="openCrop('form-uploaded-box-single', 1)">裁剪上传</div>

                                    <div class="form-uploaded-box" id="form-uploaded-box-single" style="width: 140px">
                                        {if $info.img}
                                        <div class="form-uploaded-img-box">
                                            <img class="form-uploaded-box-img" src="{:getPicture($info.img)}" data-id="{$info.img}">
                                            <i class="form-uploaded-img-preview iconfont icon-yulan" onclick="previewImg(this, 'form-uploaded-img-preview')"></i>
                                            <i class="form-uploaded-img-del iconfont icon-close" onclick="delImage(this, 'cropper_uploaded_img_ids', 'cropper_uploaded_img_paths', 'form-')"></i>
                                        </div>
                                        {/if}
                                    </div>
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row">
                                <label class="col-sm-1 col-form-label">简介</label>
                                <div class="col-sm-3">
                                    <textarea class="form-control" name="brief" rows="8">{$info.brief}</textarea>
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row">
                                <label class="col-sm-1 col-form-label">目录</label>
                                <div class="col-sm-8 layui-form-item">
                                    <div id="category-select-box">

                                    </div>
                                </div>
                                <div class="hr-line-dashed"></div>
                            </div>

                            <input type="hidden" class="category_ids" name="category_ids" value="{$info.category_ids}">

                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row">
                                <label class="col-sm-1 col-form-label">排序</label>
                                <div class="col-sm-3">
                                    <input type="number" class="form-control" name="sort" placeholder="请输入排序" value="{$info.sort}">
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row"><label class="col-sm-1 col-form-label">PPT</label>
                                <div class="col-sm-3">

                                    <div id="ppt_show">
                                        {$info.ppt_file_name ? $info.ppt_file_name : '暂未上传文件'}
                                    </div>
                                </div>

                                <div class="col-sm-3">
                                    <input type="file" id="file" accept="application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation" style="display: none">
                                    <input type="hidden" name="ppt_id" id="ppt" value="{$info['ppt_id']|default=''}"/>
                                    <button type="button" onclick="uploadPpt('file', 'ppt', 'ppt_show')" id="upload_ppt" class="btn btn-w-m btn-primary">选择PPT文件</button>
                                </div>

                            </div>

                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row">
                                <label class="col-sm-1 col-form-label">PPT名称</label>
                                <div class="col-sm-3">
                                    <input type="text" class="form-control" name="ppt_name" placeholder="请输入PPT名称" value="{$info.ppt_name}">
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row">
                                <label class="col-sm-1 col-form-label">PPT介绍</label>
                                <div class="col-sm-3">
                                    <textarea class="form-control" name="ppt_desc" rows="8">{$info.ppt_desc}</textarea>
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row">
                                <label class="col-sm-1 col-form-label"></label>
                                <div class="col-sm-2">
                                    <button type="button" class="btn btn-w-m btn-primary" onclick="addKnowledge()">新增PPT知识点</button>
                                </div>
                            </div>
                            <div id="knowledge_list">

                            </div>

                            <input type="hidden" class="ppt_knowledge" name="ppt_knowledge" value="{$info.ppt_knowledge}">

                            <div class="hr-line-dashed"></div>
                        </div>

                        <input type="hidden" name="id" value="{:input('id')}">

                        <div class="form-group row">
                            <div class="col-sm-4 col-sm-offset-2">
                                <button type="button" class="btn btn-w-m btn-default back-page">返回</button>
                                <button type="button" class="btn btn-w-m btn-primary" lay-submit lay-filter="demo">提交</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!--    选择题目弹框    -->
<div class="modal inmodal" id="choose" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content animated flipIn">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">选择题目</h4>
            </div>
            <div class="modal-body" style="height: 500px; overflow-y: scroll">
                <div class="search">
                    <input type="text" class="form-control choose_search" placeholder="输入关键词搜索" style="width: 67%;float: left">
                    <button type="button" class="btn btn-w-m btn-primary" onclick="chooseSearch()" style="float: right">搜索</button>
                </div>
                <div style="clear: both"></div>
                <div class="topic-box">

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white close-model" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="confirmChoose">保存</button>
            </div>
        </div>
    </div>
</div>

<!--    预览题目弹框    -->
<div class="modal inmodal" id="preview" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content animated flipIn">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">查看已选题目</h4>
            </div>
            <div class="modal-body" style="height: 500px; overflow-y: scroll">
                <div class="topic-box">

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white close-model" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="confirmPreview">保存</button>
            </div>
        </div>
    </div>
</div>

{include file="public/cropper-img-mask" cropper_uploaded_img_ids="cropper_uploaded_img_ids" cropper_uploaded_img_paths="cropper_uploaded_img_paths" crop_preview_box="crop-preview-box" /}{include file="public/preview-img-mask" swiper-id="cropper-preview" /}

{/block}

{block name='js'}
<script src="__STATIC__/layui-select/layui.js"></script>

<script>
    var category_list = `{$category_list}` ? JSON.parse(`{$category_list}`) : [];
    var category_ids = `{$category_ids}` ? JSON.parse(`{$category_ids}`) : [];
    layui.config({
        base: '__STATIC__/layui-select'
    }).extend({
        selectN: './layui_extends/selectN',
        selectM: './layui_extends/selectM',
    }).use(['layer', 'form', 'jquery', 'selectN'], function () {
        $ = layui.jquery;
        var form = layui.form
          , selectN = layui.selectN

        //无限级分类-基本配置
        var categorySelect = selectN({
            //元素容器【必填】
            elem: '#category-select-box'
            , search: [false, true]
            //候选数据【必填】
            , data: category_list
            , selected: category_ids
        });

        form.on('submit(demo)', function (data) {
            new Promise(resolve => {
                if (knowledge_list.length > 0) {
                    $('.ppt_knowledge').val(JSON.stringify(knowledge_list))
                    resolve()
                }
            }).then(() => {
                if (!categorySelect.isSelected) {
                    layer.msg('请完善目录');
                    return;
                }
                var formData = data.field;
                formData.category_ids = formData['category-select-box']
                formData.ppt_knowledge = $('.ppt_knowledge').val();

                var index = layer.load(2, {shade: [0.2, '#000']});

                new Promise(resolve => {
                    $.post("{:url('doCourse')}", formData, function (res) {
                        if (res.result > -1) {
                            layer.msg(res.msg);
                            resolve(res)
                        } else {
                            layer.close(index);
                            layer.msg(res.msg);
                        }
                    }, 'json');
                }).then(res => {
                    // res.result ==> 课程id
                    if(ppt_file){
                        setTimeout(function () {
                            layer.msg('请等待PPT文件上传完成');

                            // 上传PPT
                            var formData = new FormData();
                            formData.append('file', ppt_file);
                            formData.append('extendParams', JSON.stringify({courseId: res.result.toString()}));
                            formData.append('callbackUrl', 'http://xuexi.haozhuge.com.cn/index/Notice/uploadPptFileNotice');
                            $.ajax({
                                url: 'http://39.98.38.175:8081/api/file/upload',
                                type: "post",
                                data: formData,
                                contentType: false,
                                processData: false,
                                success: function (data) {
                                    if (data.status == 0 && data.fileIndex) {
                                        $.post("{:url('/Index/Api/updateCourseFileIndex')}", {
                                            course_id: res.result,
                                            file_index: data.fileIndex
                                        }, function () {
                                            setTimeout(function () {
                                                layer.msg('PPT文件上传完成');
                                                window.location.href = res.url;
                                            }, 1000)
                                        })
                                    } else {
                                        setTimeout(function () {
                                            layer.msg('PPT文件上传失败');
                                            window.location.href = res.url;
                                        }, 1000)
                                    }
                                }
                            })
                        }, res.timer)
                    }else{
                        setTimeout(function (){
                            window.location.href = "{:url('courseList')}";
                        },1000)
                    }

                })
            })
        })
    })

    /**
     * 上传文件
     * @param    file_id         file上传按钮id
     * @param    file            文件id隐藏域
     * @param    file_btn        文件上传按钮id
     * */
    var ppt_file;

    function uploadPpt(file_id, file, file_btn) {
        $("#" + file_id).trigger("click");
        $('#' + file_id).change(function () {
            var pic = $(this)[0].files[0];
            var formData = new FormData();
            var url = "/Upload/UploadFile/uploadFile";

            formData.append('download', pic);

            ppt_file = pic;

            var xhr = new XMLHttpRequest();

            //上传中设置上传的百分比
            xhr.upload.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {
                    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                    if (percentComplete == 100) {
                        clearFile(file_id);
                    } else {
                        $('#' + file_btn).html('已上传' + percentComplete + '%');
                    }
                } else {
                    console.log('无法计算')
                }
            }, false);

            xhr.addEventListener("load", function (evt) {
                //上传成功
                var response = evt.currentTarget.response ? JSON.parse(evt.currentTarget.response) : [];
                if (response.status == 1) {
                    var id = response.data.id;
                    var former_file_name = response.data.former_file_name

                    $('#' + file).val(id);
                    $('#' + file_btn).html(former_file_name);
                } else {
                    layer.msg(response.info);
                }
            }, false);

            xhr.open("POST", url);
            xhr.send(formData)
        });
    }

    var topic_list = {$topic_list};
    console.log(topic_list)

    var knowledge_list = {$ppt_knowledge};
    if (knowledge_list.length == 0) {
        var knowledge_list = [
            {
                id: 0,
                knowledge_name: '',
                ppt_start_page: '',
                ppt_end_page: '',
                topic_ids: []// 题目id集合
            }
        ];
    }

    /**
     * 深复制
     * @param data 数据
     * */
    function onlyCopy(data) {
        return JSON.parse(JSON.stringify(data));
    }

    // 新增PPT知识点
    function addKnowledge() {
        var copy_knowledge_list = onlyCopy(knowledge_list);
        copy_knowledge_list.push({
            id: 0,
            knowledge_name: '',
            ppt_start_page: '',
            ppt_end_page: '',
            topic_ids: []
        });
        renderKnowledge(copy_knowledge_list);
    }

    // 删除知识点
    function delKnowledge(index, id) {
        new Promise(resolve => {
            var msg = $(this).data('msg') ? $(this).data('msg') : '您确认删除吗？';
            swal({
                title: msg,
                type: "warning",
                cancelButtonText: '取消',
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                closeOnConfirm: false
            }, function (isConfirm) {
                if (isConfirm) {
                    // 加载层
                    var index = layer.load(2, {shade: [0.2, '#000']});

                    $.post(`{:url('/Index/Api/delKnowledge')}`, {id}, res => {
                        layer.close(index);
                        swal({
                            title: "...",
                            text: "...",
                            timer: 0,
                            showConfirmButton: false
                        });
                        resolve();
                    }, 'JSON')
                }
            });
        }).then(() => {
            var copy_knowledge_list = onlyCopy(knowledge_list);
            copy_knowledge_list.splice(index, 1);
            renderKnowledge(copy_knowledge_list);
        })
    }

    renderKnowledge(knowledge_list);

    // 渲染PPT知识点
    function renderKnowledge(copy_knowledge_list) {
        var html = '';
        if (copy_knowledge_list.length > 0) {
            copy_knowledge_list.forEach((val, key) => {
                var {id, knowledge_name, ppt_start_page, ppt_end_page, topic_ids} = val;
                html += `<div class="form-group row">
                                    <label class="col-sm-1 col-form-label">` + (key == 0 ? 'PPT知识点' : '') + `</label>
                                    <div class="col-sm-2">
                                        <input type="text" class="form-control knowledge_name" placeholder="请输入知识点名称" value="${knowledge_name}">
                                    </div>
                                    <div class="col-sm-2">
                                        <input type="number" class="form-control ppt_start_page" placeholder="请输入ppt跳转页数" value="${ppt_start_page}">
                                    </div>
                                    <div class="col-sm-2">
                                        <input type="number" class="form-control ppt_end_page" placeholder="请输入ppt结束页数" value="${ppt_end_page}">
                                    </div>
                                    <div class="col-sm-2">
                                        <button type="button" onclick="openPreview(${key})" class="btn btn-w-m btn-primary" data-toggle="modal" data-target="#preview">已选${topic_ids.length}题，点击查看已选题目</button>
                                    </div>
                                    <div class="col-sm-1">
                                        <button type="button" onclick="openChoose(${key})" class="btn btn-w-m btn-primary" data-toggle="modal" data-target="#choose">选择题目</button>
                                    </div>
                                    <div class="col-sm-1">
                                        <button type="button" onclick="delKnowledge(${key}, ${id})" class="btn btn-w-m btn-danger">删除知识点</button>
                                    </div>
                                </div>`;
            })
        }

        knowledge_list = copy_knowledge_list;
        $('#knowledge_list').html(html);
    }

    // 修改知识点名称
    $(document).on('blur', '.knowledge_name', function () {
        var value = $(this).val();
        var index = $(this).index('.knowledge_name');
        var copy_knowledge_list = onlyCopy(knowledge_list);
        copy_knowledge_list[index].knowledge_name = value;
        renderKnowledge(copy_knowledge_list);
    })

    // 修改ppt跳转页数
    $(document).on('blur', '.ppt_start_page', function () {
        var value = $(this).val();
        var index = $(this).index('.ppt_start_page');
        var copy_knowledge_list = onlyCopy(knowledge_list);
        copy_knowledge_list[index].ppt_start_page = value;
        renderKnowledge(copy_knowledge_list);
    })

    // 修改ppt结束页数
    $(document).on('blur', '.ppt_end_page', function () {
        var value = $(this).val();
        var index = $(this).index('.ppt_end_page');
        var copy_knowledge_list = onlyCopy(knowledge_list);
        copy_knowledge_list[index].ppt_end_page = value;
        renderKnowledge(copy_knowledge_list);
    })

    function subText(string, len = 100){
        if(string.length > len){
            return string.substr(0, len) + '...';
        }else{
            return string;
        }
    }

    /**
     * 获取题目html数据
     * @param choose true：选择题目，false：预览题目
     * @param val 题目数据
     * @param key 下标
     * @param is_active 是否选中
     * @param search_value 搜索内容
     * */
    function getTopicHtml(choose, val, key, is_active, search_value = '') {
        var topic = '';

        var stem_text = '';
        var stem_text_search = '';
        var text = '';
        var text_search = '';
        var img = '';

        var tags_search = val.tags;
        var show_tags = tags_search ? "【" + tags_search + "】" : ""

        if (val.type == 2) {
            var sub_question_stem = subText(val.question_stem);
            stem_text = `<div class="text">${show_tags}${sub_question_stem}</div>`
            stem_text_search = val.question_stem;
        }else{
            if (val.question.text !== '') {
                text = `<div class="text">${show_tags}${val.question.text}</div>`;
                text_search = val.question.text;
            }

            if (val.question.img !== '') img = `<img src="${val.question.img}">`;
        }

        if (!choose) {
            // 预览已选题目
            if (is_active) {
                topic += `<div class="topic active" data-id="${val.id}">
                            ${stem_text}
                            ${text}
                            ${img}
                        </div>`;
            }
        } else {
            // 选择题目
            var display = (text_search.indexOf(search_value) > -1 || stem_text_search.indexOf(search_value) > -1 || tags_search.indexOf(search_value) > -1) ? 'block' : 'none';
            topic += `<div class="topic ` + (is_active ? 'active' : '') + `" data-id="${val.id}" style="display: ${display}">
                            ${stem_text}
                            ${text}
                            ${img}
                        </div>`;
        }

        return topic;
    }

    /**
     * 渲染题目列表
     * @param choose true：选择题目，false：预览题目
     * @param index 【选择题目】按钮下标
     * @param search_value 搜索内容
     * */
    function renderTopicList(choose = true, index = 0, search_value = '') {
        var topic = '';
        if (topic_list) {
            topic_list.forEach((val, key) => {
                if (!choose) {
                    // 预览已选题目

                    // console.log(knowledge_list[index].topic_ids)
                    // console.log(typeof val.id, val.id)
                    var is_active = knowledge_list[index].topic_ids.length > 0 ? (knowledge_list[index].topic_ids.indexOf(val.id.toString()) > -1 ? true : false) : false;

                    topic += getTopicHtml(choose, val, key, is_active);
                    $('#preview .topic-box').html(topic)
                } else {
                    // 选择题目
                    // console.log(knowledge_list[index].topic_ids)
                    // console.log(typeof val.id, val.id)

                    var is_active = knowledge_list[index].topic_ids.length > 0 ? (knowledge_list[index].topic_ids.indexOf(val.id.toString()) > -1 ? true : false) : false;

                    topic += getTopicHtml(choose, val, key, is_active, search_value);

                    $('#choose .topic-box').html(topic)
                }
            })
        }
    }

    // 点击题目（选中/取消选中）
    $(document).on('click', '.topic', function () {
        var is_active = $(this).is('.active');
        if (is_active) {
            // 取消选中
            $(this).removeClass('active');
        } else {
            // 选中
            $(this).addClass('active');
        }
    })

    // 打开选择框
    var choose_topic_btn_index = 0;

    function openChoose(index) {
        $('.choose_search').val('');
        choose_topic_btn_index = index;
        renderTopicList(true, index);
    }

    // 选择框搜索
    function chooseSearch() {
        var value = $('.choose_search').val();

        renderTopicList(true, choose_topic_btn_index, value);
    }

    // 选择题目弹出框点击保存
    $(document).on('click', '#confirmChoose', function () {
        var topic_ids = [];
        $('#choose .active').each((key, val) => {
            var id = $(val).data('id').toString();
            topic_ids.push(id)
        })
        knowledge_list[choose_topic_btn_index].topic_ids = topic_ids;

        renderKnowledge(knowledge_list);

        $(".close-model").trigger("click");
    })

    // 打开预览框
    var preview_topic_btn_index = 0;

    function openPreview(index) {
        preview_topic_btn_index = index;
        renderTopicList(false, index);
    }

    // 预览题目弹出框点击保存
    $(document).on('click', '#confirmPreview', function () {
        var topic_ids = [];
        $('#preview .active').each((key, val) => {
            var id = $(val).data('id');
            topic_ids.push(id)
        })
        knowledge_list[choose_topic_btn_index].topic_ids = topic_ids;

        renderKnowledge(knowledge_list);

        $(".close-model").trigger("click");
    })

</script>{/block}